package C709;

/**
 * 编写程序实现  4个线程，其中两个线程每次对j增加1，另外两个线程对j每次减少1
 * （要求：程序使用内部类实现线程，对j增减的时候可以不考虑顺序问题 ）
 *
 * @author: luolidong
 * @create: 2021-07-11 18:53
 * @version: 1.0
 */
public class Demo {
    private int j = 0;

    /**
     * @Description: +1方法
     * @Param: []
     * @return: void
     */
    private synchronized void increase() {
        j++;
        System.out.println(Thread.currentThread().getName() + ": j=" + j);

    }

    /**
     * @Description: -1方法
     * @Param: []
     * @return: void
     */
    private synchronized void decrease() {
        j--;
        System.out.println(Thread.currentThread().getName() + ": j=" + j);

    }

    /**
     * +1内部类
     */
    public class incRunnable implements Runnable {

        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                Demo.this.increase();
            }
        }
    }

    /**
     * -1内部类
     */
    public class decRunnable implements Runnable {

        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                Demo.this.decrease();
            }
        }
    }

    public static void main(String[] args) {
        Demo demo = new Demo();
        //创建两个内部类对象
        incRunnable incRunnable = demo.new incRunnable();
        decRunnable decRunnable = demo.new decRunnable();
        //创建并启动两个+1线程
        for (int i = 1; i <= 2; i++) {
            Thread thread = new Thread(incRunnable, "inc" + i);
            thread.start();
        }
        //创建并启动两个-1线程
        for (int i = 1; i <= 2; i++) {
            Thread thread = new Thread(decRunnable, "dec" + i);
            thread.start();
        }
    }
}
